package cn.sunyblog.tool.threadpool;

import cn.sunyblog.tool.threadpool.config.DynamicThreadPoolConfig;

import java.util.concurrent.TimeUnit;

/**
 * 线程池扩容缩容Bug测试
 * 用于验证队列使用率为0但仍触发扩容的问题修复
 * 
 * @author sunyblog
 */
public class ThreadPoolBugTest {
    
    public static void main(String[] args) throws InterruptedException {
        // 创建线程池配置
        DynamicThreadPoolConfig config = new DynamicThreadPoolConfig();
        config.setThreadPoolName("TestPool");
        config.setCorePoolSize(5);
        config.setMaximumPoolSize(10);
        config.setQueueCapacity(20);
        config.setMonitorInterval(2); // 2秒监控间隔
        config.setEnableMetricsLogging(true);
        
        // 创建动态线程池
        DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(config);
        
        System.out.println("=== 开始测试线程池扩容缩容逻辑 ===");
        
        // 阶段1：高负载测试 - 触发扩容
        System.out.println("\n阶段1：高负载测试（预期：触发扩容）");
        for (int i = 0; i < 50; i++) {
            try {
                executor.execute(() -> {
                    try {
                        Thread.sleep(1000); // 模拟耗时任务
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
            } catch (Exception e) {
                System.out.println("任务被拒绝: " + e.getMessage());
            }
        }
        
        // 等待一段时间观察扩容
        Thread.sleep(10000);
        
        // 阶段2：低负载测试 - 触发缩容
        System.out.println("\n阶段2：低负载测试（预期：触发缩容）");
        for (int i = 0; i < 3; i++) {
            executor.execute(() -> {
                try {
                    Thread.sleep(500); // 模拟轻量任务
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        
        // 等待观察缩容
        Thread.sleep(15000);
        
        // 阶段3：无负载测试
        System.out.println("\n阶段3：无负载测试（预期：进一步缩容）");
        Thread.sleep(10000);
        
        System.out.println("\n=== 测试完成 ===");
        executor.shutdown();
        
        try {
            if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }
}